<template>
    <view class="container">
      <view class="profile-list">
        <!-- 头像 -->
        <view class="profile-item" @click="chooseAvatar">
          <text class="item-label">头像</text>
          <view class="item-content">
            <image class="avatar" :src="userInfo.avatar ? (config.staticUrl + userInfo.avatar) : '/static/img/default-avatar.png'" mode="aspectFill"></image>
            <text class="iconfont icon-right"></text>
          </view>
        </view>
        
        <!-- 昵称 -->
        <view class="profile-item" @click="editNickname">
          <text class="item-label">昵称</text>
          <view class="item-content">
            <text class="item-value">{{userInfo.nickName || '未设置'}}</text>
            <text class="iconfont icon-right"></text>
          </view>
        </view>
        
        <!-- 用户名 -->
        <view class="profile-item">
          <text class="item-label">用户名</text>
          <view class="item-content">
            <text class="item-value">{{userInfo.userName}}</text>
          </view>
        </view>
        
        <!-- 手机号 -->
        <view class="profile-item" @click="editPhone">
          <text class="item-label">手机号</text>
          <view class="item-content">
            <text class="item-value">{{userInfo.phonenumber || '未绑定'}}</text>
            <text class="iconfont icon-right"></text>
          </view>
        </view>
        
        <!-- 邮箱 -->
        <view class="profile-item" @click="editEmail">
          <text class="item-label">邮箱</text>
          <view class="item-content">
            <text class="item-value">{{userInfo.email || '未绑定'}}</text>
            <text class="iconfont icon-right"></text>
          </view>
        </view>
        
        <!-- 性别 -->
        <view class="profile-item" @click="editGender">
          <text class="item-label">性别</text>
          <view class="item-content">
            <text class="item-value">{{genderText}}</text>
            <text class="iconfont icon-right"></text>
          </view>
        </view>

        <!-- 修改密码 -->
        <view class="profile-item" @click="goToChangePwd">
          <text class="item-label">修改密码</text>
          <view class="item-content">
            <text class="iconfont icon-right"></text>
          </view>
        </view>

        <!-- 管理后台 -->
        <view class="profile-item" @click="goToAdmin">
          <text class="item-label">管理后台</text>
          <view class="item-content">
            <text class="iconfont icon-right"></text>
          </view>
        </view>
      </view>
    </view>
  </template>
  
  <script>
  import storage from '../../utils/storage'
  import constant from '../../utils/constant'
  import config from '../../config'
  import { getUserProfile, updateUserProfile, uploadAvatar } from '../../api/user.js'
  
  export default {
    data() {
      return {
        config,
        userInfo: {
          avatar: '',
          nickName: '',
          userName: '',
          phonenumber: '',
          email: '',
          sex: '0'
        }
      }
    },
    computed: {
      genderText() {
        const genderMap = {
          '0': '未设置',
          '1': '男',
          '2': '女'
        }
        return genderMap[this.userInfo.sex] || '未设置'
      }
    },
    onLoad() {
      this.getUserProfile()
    },
    onShow() {
      // 页面显示时刷新数据，以获取从编辑页面返回后的最新数据
      this.getUserProfile()
    },
    methods: {
      // 获取用户信息
      getUserProfile() {
        uni.showLoading({
          title: '加载中...'
        })
        getUserProfile().then(res => {
          if (res.code === 200) {
            this.userInfo = res.data
            // 更新本地存储的用户信息
            storage.set(constant.avatar, res.data.avatar)
            storage.set(constant.nickname, res.data.nickName)
            storage.set(constant.name, res.data.userName)
          }
        }).finally(() => {
          uni.hideLoading()
        })
      },
      
      // 选择头像
      chooseAvatar() {
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0]
            this.uploadAvatarFile(tempFilePath)
          }
        })
      },
      
      // 上传头像文件
      uploadAvatarFile(filePath) {
        uni.showLoading({
          title: '上传中...',
          mask: true
        })
        
        // 构建FormData
        const formData = new FormData()
        formData.append('avatarfile', {
          uri: filePath,
          type: 'image/jpeg',
          name: 'avatar.jpg'
        })
        
        uploadAvatar(formData).then(res => {
          if (res.code === 200) {
            this.userInfo.avatar = res.imgUrl
            storage.set(constant.avatar, res.imgUrl)
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: res.msg || '上传失败',
              icon: 'none'
            })
          }
        }).catch(() => {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
      
      // 修改昵称
      editNickname() {
        uni.navigateTo({
          url: '/pages/my/edit?type=nickname&value=' + (this.userInfo.nickName || '')
        })
      },
      
      // 修改手机号
      editPhone() {
        uni.navigateTo({
          url: '/pages/my/edit?type=phone&value=' + (this.userInfo.phonenumber || '')
        })
      },
      
      // 修改邮箱
      editEmail() {
        uni.navigateTo({
          url: '/pages/my/edit?type=email&value=' + (this.userInfo.email || '')
        })
      },
      
      // 修改性别
      editGender() {
        uni.showActionSheet({
          itemList: ['男', '女'],
          success: (res) => {
            const gender = res.tapIndex + 1
            this.updateUserInfo({
              sex: gender.toString()
            })
          }
        })
      },
      
      // 更新用户信息
      updateUserInfo(data) {
        uni.showLoading({
          title: '更新中...'
        })
        updateUserProfile(data).then(res => {
          if (res.code === 200) {
            uni.showToast({
              title: '更新成功',
              icon: 'success'
            })
            this.getUserProfile()
          } else {
            uni.showToast({
              title: res.msg || '更新失败',
              icon: 'none'
            })
          }
        }).finally(() => {
          uni.hideLoading()
        })
      },

      // 跳转到修改密码页面
      goToChangePwd() {
        uni.navigateTo({
          url: '/pages/my/password'
        })
      },

      // 跳转到后台管理系统
      goToAdmin() {
        // 开发环境下的后台地址
        const adminUrl = 'http://localhost:81';
        
        // 使用web-view组件打开网页
        uni.navigateTo({
          url: `/pages/webview/index?url=${encodeURIComponent(adminUrl)}`
        });
      }
    }
  }
  </script>
  
  <style>
  .container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 20rpx;
  }
  
  .profile-list {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 20rpx;
  }
  
  .profile-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;
  }
  
  .profile-item:last-child {
    border-bottom: none;
  }
  
  .item-label {
    font-size: 28rpx;
    color: #333;
  }
  
  .item-content {
    display: flex;
    align-items: center;
  }
  
  .item-value {
    font-size: 28rpx;
    color: #666;
    margin-right: 10rpx;
  }
  
  .avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    margin-right: 10rpx;
  }
  
  .icon-right {
    color: #999;
    font-size: 24rpx;
  }
  </style>
